package com.jzlx.websocket;

import com.alibaba.fastjson2.JSON;
import com.jzlx.domain.DiskSpaceInfo;
import com.jzlx.domain.MassageInfo;
import com.jzlx.domain.MemoryInfo;
import com.jzlx.utils.OSHIUtil;

import javax.websocket.*;
import java.io.IOException;

/**
 * @description:
 * @author: zhulei
 * @create: 2025-03-24 17:40
 **/
@ClientEndpoint
public class WebSocketClient {

    private static int onlineCount = 0;


    @OnOpen
    public void onOpen(Session session) {
        addOnlineCount();
        System.out.println("Connected to server: " + session.getRequestURI());
        System.out.println("current connection: " + onlineCount);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("Received message from server: " + message);
        if (message.equals("pong")) {
            System.out.println("the connection is normal");
        }
        if (message.equals("request")) {
            System.out.println("request data by " + session.getRequestURI().getPath());
            MassageInfo info = new MassageInfo(OSHIUtil.getOperatingSystemInfo(), OSHIUtil.getCpuInfo(), OSHIUtil.getMemoryInfo(MemoryInfo.MB), OSHIUtil.getDiskSpaceInfo(DiskSpaceInfo.GB));
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(info));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        subOnlineCount(); // 通知主线程连接已关闭
        System.out.println("Connection closed: " + closeReason);
        System.out.println("current connection: " + onlineCount);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        subOnlineCount(); // 通知主线程连接已关闭
        throwable.printStackTrace();
        System.out.println("Error occurred: " + throwable.getMessage());
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketClient.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketClient.onlineCount--;
    }
}
